package com.htzy.extrace.ui.domain;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.telephony.SmsManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.htzy.extrace.baidumap.BaiduMapHistoryActivity;
import com.htzy.extrace.loader.ExpressLoader;
import com.htzy.extrace.misc.model.CustomerInfo;
import com.htzy.extrace.misc.model.ExpressSheet;
import com.htzy.extrace.net.IDataAdapter;
import com.htzy.extrace.ui.main.ExTraceApplication;
import com.htzy.extrace.ui.main.MainActivity;
import com.htzy.extrace.ui.main.R;
import com.htzy.extrace.ui.misc.CustomerListActivity;
import com.htzy.extrace.util.Global;
import com.zxing.activity.CaptureActivity;

public class ExpressEditActivity extends ActionBarActivity implements
		ActionBar.TabListener, IDataAdapter<ExpressSheet> {

	public static final int REQUEST_CAPTURE = 100;
	public static final int REQUEST_RCV = 101;
	public static final int REQUEST_SND = 102;

	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	private ExpressSheet mItem;

	private ExpressLoader mLoader;
	private Intent mIntent;
	private ExpressEditFragment1 baseFragment;
	private ExpressEditFragment2 externFragment;
	private boolean new_es = false; // 新建
	private Context context;

	public static final int INTENT_NEW = 1;
	public static final int INTENT_EDIT = 2;

	private static String ARG_SECTION_NUMBER = "ARG_SECTION_NUMBER";
	private static int sectionNumber;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_express_edit);
		final ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		/*
		 * Create the adapter that will return a fragment for each of the three
		 * primary sections of the activity.
		 */
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		/*
		 * Set up the ViewPager with the sections adapter.
		 */
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		/*
		 * When swiping between different sections, select the corresponding
		 * tab. We can also use ActionBar.Tab#select() to do this if we have a
		 * reference to the Tab.
		 */
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		/*
		 * For each of the sections in the app, add a tab to the action bar.
		 */
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			/*
			 * Create a tab with text corresponding to the page title defined by
			 * the adapter. Also specify this Activity object, which implements
			 * the TabListener interface, as the callback (listener) for when
			 * this tab is selected.
			 */
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
		mIntent = getIntent();
		if (mIntent.hasExtra("Action")) {
			if (mIntent.getStringExtra("Action").equals("New")) {
				new_es = true;
				StartCapture(REQUEST_CAPTURE);
			} else if (mIntent.getStringExtra("Action").equals("Query")) {
				StartCapture(REQUEST_CAPTURE);
			} else if (mIntent.getStringExtra("Action").equals("Edit")) {
				ExpressSheet es;
				if (mIntent.hasExtra("ExpressSheet")) {
					es = (ExpressSheet) mIntent
							.getSerializableExtra("ExpressSheet");
					Refresh(es.getID());
				} else {
					this.setResult(RESULT_CANCELED, mIntent);
					this.finish();
				}
			} else if (mIntent.getStringExtra("Action").equals("touristResult")) {
				Bundle bundle = this.getIntent().getExtras();
				String str = bundle.getString("touristResult");
				System.out.println(str);
				mLoader = new ExpressLoader(this, this);
				mLoader.loadExpress(str);
			} else {
				this.setResult(RESULT_CANCELED, mIntent);
				this.finish();
			}
		} else {
			this.setResult(RESULT_CANCELED, mIntent);
			this.finish();
		}

	}

	/*
	 * 对游客输入的快件序列号进行查询
	 */
	private void touristInit(String id) {
		mLoader = new ExpressLoader(this, this);
		mLoader.loadExpress(id);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		/*
		 * Inflate the menu; this adds items to the action bar if it is present.
		 */
		getMenuInflater().inflate(R.menu.express_edit, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.action_ok: {
			getMItem();
			save();
			return true;
		}
		case R.id.action_refresh: {
			if (mItem != null) {
				Refresh(mItem.getID());
			}
			return true;
		}
		case (android.R.id.home): {
			mIntent.putExtra("ExpressSheet", mItem);
			this.setResult(RESULT_OK, mIntent);
			this.finish();
			return true;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	private void getMItem() {
		externFragment.getExternInformation(mItem);
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public ExpressSheet getData() {
		return mItem;
	}

	@Override
	public void setData(ExpressSheet data) {
		mItem = data;
	}

	@Override
	public void notifyDataSetChanged() {
		// 如果要显示的快件信息为空,则退出
		if (mItem == null) {
			finish();
			return;
		}
		if (baseFragment != null) {
			baseFragment.RefreshUI(mItem);
		}
		if (externFragment != null) {
			externFragment.RefreshUI(mItem);
		}
	}

	/**
	 * 相机扫描后回调函数
	 * 
	 * @param requestCode
	 *            请求Code:REQUEST_CAPTURE,REQUEST_RCV,REQUEST_SND
	 * @param resultCode
	 *            取消扫描:0,有返回结果:-1
	 * @param data
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		CustomerInfo customer;

		switch (resultCode) {
		case RESULT_OK: {
			switch (requestCode) {
			case REQUEST_CAPTURE: {
				if (data.hasExtra("result")) {
					// 得到扫描后的快件序列号
					String id = data.getExtras().getString("result");
					System.out.println("序列号::" + id);
					try {
						mLoader = new ExpressLoader(this, this);
						if (new_es) {
							new_es = false;
							mLoader.newExpress(id);
						} else {
							mLoader.loadExpress(id);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				break;
			}
			case REQUEST_RCV:
				if (data.hasExtra("CustomerInfo")) {
					customer = (CustomerInfo) data
							.getSerializableExtra("CustomerInfo");
					mItem.setRecever(customer);
					baseFragment.displayRcv(mItem);
				}
				break;
			case REQUEST_SND:
				if (data.hasExtra("CustomerInfo")) {
					customer = (CustomerInfo) data
							.getSerializableExtra("CustomerInfo");
					mItem.setSender(customer);
					baseFragment.displaySnd(mItem);
				}
				break;
			}
			break;
		}
		case 0: {
			// 扫描时点击取消，没有返回结果
			finish();
			return;
		}
		default: {
			Toast.makeText(this, "对不起，查询的快件不存在", Toast.LENGTH_SHORT).show();
			break;
		}
		}
	}

	/**
	 * 
	 * @param id
	 */
	void Refresh(String id) {
		try {
			mLoader = new ExpressLoader(this, this);
			mLoader.loadExpress(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void save() {
		mLoader = new ExpressLoader(this, this);
		mLoader.save(mItem);
	}

	/**
	 * 开启相机
	 * 
	 */
	private void StartCapture(int request) {
		Intent intent = new Intent();
		intent.putExtra("Action", "Captrue");
		intent.setClass(this, CaptureActivity.class);
		startActivityForResult(intent, request);
	}

	private void GetCustomer(int intent_code) {
		Intent intent = new Intent();
		intent.setClass(this, CustomerListActivity.class);
		if (intent_code == REQUEST_RCV) {
			if (baseFragment.mRcvNameView.getTag() == null) {
				intent.putExtra("Action", "New");
			} else {
				intent.putExtra("Action", "New");
				intent.putExtra("CustomerInfo",
						(CustomerInfo) baseFragment.mRcvNameView.getTag());
			}
		} else if (intent_code == REQUEST_SND) {
			if (baseFragment.mSndNameView.getTag() == null) {
				intent.putExtra("Action", "New");
			} else {
				intent.putExtra("Action", "New");
				intent.putExtra("CustomerInfo",
						(CustomerInfo) baseFragment.mSndNameView.getTag());
			}
		}
		startActivityForResult(intent, intent_code);
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case 0:
				baseFragment = ExpressEditFragment1.newInstance();
				return baseFragment;
			case 1:
				externFragment = ExpressEditFragment2.newInstance();
				return externFragment;
			}
			return ExpressEditFragment1.newInstance();
		}

		@Override
		public int getCount() {
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_ex_edit1).toUpperCase(l);// 基本信息
			case 1:
				return getString(R.string.title_ex_edit2).toUpperCase(l);// 扩展信息
			}
			return null;
		}
	}

	/**
	 * 快件信息的基本信息 A placeholder fragment containing a simple view.
	 */
	public static class ExpressEditFragment1 extends Fragment {

		private TextView mIDView;
		private TextView mRcvNameView;
		private TextView mRcvTelCodeView;
		private TextView mRcvDptView;
		private TextView mRcvAddrView;
		private TextView mRcvRegionView;

		private TextView mSndNameView;
		private TextView mSndTelCodeView;
		private TextView mSndDptView;
		private TextView mSndAddrView;
		private TextView mSndRegionView;

		private TextView mRcvTimeView;

		private TextView mSndTimeView;

		private TextView mExpressStatus;

		private ImageView mbtnCapture;
		private ImageView mbtnRcv;
		private ImageView mbtnSnd;
		private ImageView call;
		private ImageView msg;
		String tel = "10086";
		int state = ExpressSheet.STATUS.STATUS_CREATED;

		public static ExpressEditFragment1 newInstance() {
			ExpressEditFragment1 fragment = new ExpressEditFragment1();
			return fragment;
		}

		public ExpressEditFragment1() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_express_edit1,
					container, false);
			mIDView = (TextView) rootView.findViewById(R.id.expressId);
			mRcvNameView = (TextView) rootView
					.findViewById(R.id.expressRcvName);
			mRcvTelCodeView = (TextView) rootView
					.findViewById(R.id.expressRcvTel);
			mRcvAddrView = (TextView) rootView
					.findViewById(R.id.expressRcvAddr);
			mRcvDptView = (TextView) rootView.findViewById(R.id.expressRcvDpt);
			mRcvRegionView = (TextView) rootView
					.findViewById(R.id.expressRcvRegion);

			mSndNameView = (TextView) rootView
					.findViewById(R.id.expressSndName);
			mSndTelCodeView = (TextView) rootView
					.findViewById(R.id.expressSndTel);
			mSndAddrView = (TextView) rootView
					.findViewById(R.id.expressSndAddr);
			mSndDptView = (TextView) rootView.findViewById(R.id.expressSndDpt);
			mSndRegionView = (TextView) rootView
					.findViewById(R.id.expressSndRegion);

			mRcvTimeView = (TextView) rootView
					.findViewById(R.id.expressAccTime);
			mSndTimeView = (TextView) rootView
					.findViewById(R.id.expressDlvTime);

			mExpressStatus = (TextView) rootView
					.findViewById(R.id.expressStatus);

			/**
			 * 运单号按钮事件
			 */
			mbtnCapture = (ImageView) rootView
					.findViewById(R.id.action_ex_capture_icon);
			mbtnCapture.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					((ExpressEditActivity) getActivity())
							.StartCapture(REQUEST_CAPTURE);
				}
			});
			/**
			 * 收件人按钮事件
			 */
			mbtnRcv = (ImageView) rootView
					.findViewById(R.id.action_ex_rcv_icon);
			mbtnRcv.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					((ExpressEditActivity) getActivity())
							.GetCustomer(REQUEST_RCV);
				}
			});

			/**
			 * 发件人按钮事件
			 */
			mbtnSnd = (ImageView) rootView
					.findViewById(R.id.action_ex_snd_icon);
			mbtnSnd.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					((ExpressEditActivity) getActivity())
							.GetCustomer(REQUEST_SND);
				}
			});

			call = (ImageView) rootView.findViewById(R.id.call);

			msg = (ImageView) rootView.findViewById(R.id.msg);
			return rootView;
		}

		/**
		 * 刷新收件信息界面
		 * 
		 * @param es
		 */
		void RefreshUI(ExpressSheet es) {
			mIDView.setText(es.getID());
			displayRcv(es);
			displaySnd(es);
			if (es.getAccepterTime() != null) {
				mRcvTimeView
						.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
								.format(es.getAccepterTime()));
			}

			else
				mRcvTimeView.setText(null);
			if (es.getDeleveTime() != null) {
				mSndTimeView
						.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
								.format(es.getDeleveTime()));

			} else
				mSndTimeView.setText(null);
			displayBtn(es);
		}

		void displayBtn(ExpressSheet es) {
			// 按钮状态控制
			if (es.getStatus() == ExpressSheet.STATUS.STATUS_CREATED) {
				mbtnRcv.setVisibility(View.VISIBLE);
				mbtnSnd.setVisibility(View.VISIBLE);
			} else {
				mbtnRcv.setVisibility(View.INVISIBLE);
				mbtnSnd.setVisibility(View.INVISIBLE);
			}
			if (es.getStatus() == ExpressSheet.STATUS.STATUS_DISPATCHED) {
				call.setVisibility(View.VISIBLE);
				msg.setVisibility(View.VISIBLE);
			} else {
				call.setVisibility(View.INVISIBLE);
				msg.setVisibility(View.INVISIBLE);
			}
			switch (es.getStatus()) {
			case ExpressSheet.STATUS.STATUS_CREATED: {
				mExpressStatus.setText("新建");
				break;
			}
			case ExpressSheet.STATUS.STATUS_RECEIVED: {
				mExpressStatus.setText("揽收");
				break;
			}
			case ExpressSheet.STATUS.STATUS_PARTATION: {
				mExpressStatus.setText("分拣");
				break;
			}
			case ExpressSheet.STATUS.STATUS_TRANSPORT: {
				mExpressStatus.setText("转运");
				break;
			}
			case ExpressSheet.STATUS.STATUS_DISPATCHED: {
				mExpressStatus.setText("派送中");
				break;
			}
			case ExpressSheet.STATUS.STATUS_DELIVERIED: {
				mExpressStatus.setText("已交付");
				break;
			}
			}
		}

		/**
		 * 显示收件人信息
		 * 
		 * @param es
		 */
		void displayRcv(ExpressSheet es) {
			if (es.getRecever() != null) {
				mRcvNameView.setText(es.getRecever().getName());
				mRcvTelCodeView.setText(es.getRecever().getTelCode());
				mRcvNameView.setTag(es.getRecever());
				mRcvAddrView.setText(es.getRecever().getAddress());
				mRcvDptView.setText(es.getRecever().getDepartment());
				mRcvRegionView.setText(es.getRecever().getRegionString());
				tel = es.getRecever().getTelCode();
				state = es.getStatus();
			} else {
				mRcvNameView.setText(null);
				mRcvTelCodeView.setText(null);
				mRcvNameView.setTag(null);
				mRcvAddrView.setText(null);
				mRcvDptView.setText(null);
				mRcvRegionView.setText(null);
			}
			call.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (state == ExpressSheet.STATUS.STATUS_DISPATCHED) {
						String number = tel;
						if (ExTraceApplication.isISDEUBG()) {
							tel = "18337136329";
						}
						Intent intent = new Intent();
						intent.setAction("android.intent.action.CALL");
						Toast.makeText(getActivity(), "打电话给:" + number,
								Toast.LENGTH_SHORT).show();
						intent.setData(Uri.parse("tel:" + tel));
						startActivity(intent);
					} else {
						Toast.makeText(getActivity(), "未派送的快件不可联系收件人:(",
								Toast.LENGTH_SHORT).show();
						return;
					}

				}
			});
			msg.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (state == ExpressSheet.STATUS.STATUS_DISPATCHED) {
						String sms_content = ExTraceApplication.getMsg();
						String phone_number = tel;
						if (ExTraceApplication.isISDEUBG()) {
							phone_number = "10086";
						}
						if (phone_number.equals("")) {
							Toast.makeText(getActivity(), "null number is err",
									Toast.LENGTH_LONG).show();
						} else {
							SmsManager smsManager = SmsManager.getDefault();
							if (sms_content.length() > 70) {
								List<String> contents = smsManager
										.divideMessage(sms_content);
								for (String sms : contents) {
									smsManager.sendTextMessage(phone_number,
											null, sms, null, null);
								}
							} else {
								smsManager.sendTextMessage(phone_number, null,
										sms_content, null, null);
							}
							Toast.makeText(getActivity(), "success",
									Toast.LENGTH_SHORT).show();
						}

						Toast.makeText(getActivity(), "发送成功:)",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getActivity(), "未派送的快件不可联系收件人:(",
								Toast.LENGTH_SHORT).show();
						return;
					}
				}
			});
		}

		/**
		 * 显示发件人信息
		 * 
		 * @param es
		 */
		void displaySnd(ExpressSheet es) {
			if (es.getSender() != null) {
				mSndNameView.setText(es.getSender().getName());
				mSndTelCodeView.setText(es.getSender().getTelCode());
				mSndNameView.setTag(es.getSender());
				mSndAddrView.setText(es.getSender().getAddress());
				mSndDptView.setText(es.getSender().getDepartment());
				mSndRegionView.setText(es.getSender().getRegionString());
			} else {
				mSndNameView.setText(null);
				mSndTelCodeView.setText(null);
				mSndNameView.setTag(null);
				mSndAddrView.setText(null);
				mSndDptView.setText(null);
				mSndRegionView.setText(null);
			}
		}
	}

	/**
	 * 快件信息的扩展信息（快件或者包裹的详细信息）
	 * 
	 * @author liujiangfeng
	 */
	public static class ExpressEditFragment2 extends Fragment {

		private static final String[] types = { "普通快件", "当日达快件", "优先配送", "航空件" };

		Spinner spinner;
		ArrayAdapter<String> type;
		private int typeNum = 0;

		private EditText weight;
		private EditText tranfee;
		private EditText packagefee;
		private EditText insufee;
		private TextView accepter;
		private TextView deliver;
		private Button transpackage_history;
		private Button package_route;

		public ExpressEditFragment2() {
		}

		public void getExternInformation(ExpressSheet mItem) {
			mItem.setType(typeNum);
			if (weight.getText().toString().equals("")
					|| weight.getText().toString() == null) {
			} else {
				mItem.setWeight(Float.valueOf(weight.getText().toString()));
			}
			if (tranfee.getText().toString().equals("")
					|| tranfee.getText().toString() == null) {
			} else {
				mItem.setTranFee(Float.valueOf(tranfee.getText().toString()));
			}
			if (packagefee.getText().toString().equals("")
					|| packagefee.getText().toString() == null) {
			} else {
				mItem.setPackageFee(Float.valueOf(packagefee.getText()
						.toString()));
			}
			if (insufee.getText().toString().equals("")
					|| insufee.getText().toString() == null) {
			} else {
				mItem.setInsuFee(Float.valueOf(insufee.getText().toString()));
			}
		}

		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static ExpressEditFragment2 newInstance() {
			ExpressEditFragment2 fragment = new ExpressEditFragment2();
			return fragment;
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_express_edit2,
					container, false);
			// inflater.setContentView(android.R.layout.simple_spinner_item);
			spinner = (Spinner) rootView.findViewById(R.id.type);

			weight = (EditText) rootView.findViewById(R.id.weight);
			tranfee = (EditText) rootView.findViewById(R.id.tranfee);
			packagefee = (EditText) rootView.findViewById(R.id.packagefee);
			insufee = (EditText) rootView.findViewById(R.id.insufee);
			accepter = (TextView) rootView.findViewById(R.id.accepter);
			deliver = (TextView) rootView.findViewById(R.id.deliver);
			// deliver_tel = (TextView) rootView.findViewById(R.id.deliver_tel);
			package_route = (Button) rootView.findViewById(R.id.package_route);
			transpackage_history = (Button) rootView
					.findViewById(R.id.transpackage_history);

			// 将可选内容与ArrayAdapter连接起来
			type = new ArrayAdapter<String>(getActivity(),
					android.R.layout.simple_spinner_item, types);
			// 设置下拉列表的风格
			type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			// 将adapter 添加到spinner中,快件类型选择
			spinner.setAdapter(type);
			// 添加事件Spinner事件监听
			spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					typeNum = arg2;
				}

				public void onNothingSelected(AdapterView<?> arg0) {
				}
			});
			spinner.setVisibility(View.VISIBLE);
			return rootView;
		}

		/**
		 * 刷新件信息界面
		 * 
		 * @param es
		 */
		void RefreshUI(ExpressSheet es) {
			spinner.setSelection(es.getType());
			if (es.getWeight() != null) {
				weight.setText(es.getWeight() + "");
			}
			if (es.getTranFee() != null) {
				tranfee.setText(es.getTranFee() + "");
			}
			if (es.getPackageFee() != null) {
				packagefee.setText(es.getPackageFee() + "");
			}
			if (es.getInsuFee() != null) {
				insufee.setText(es.getInsuFee() + "");
			}
			if (es.getAccepter() != null) {
				accepter.setText(es.getAccepter() + "");
			}
			if (es.getDeliver() != null) {
				deliver.setText(es.getDeliver() + "");
			}
			displayBtn(es);
		}

		private void displayBtn(ExpressSheet es) {
			final String ExpressId = es.getID();
			transpackage_history.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.putExtra("ExpressId", ExpressId);
					intent.setClass(getActivity(), ExpressHistoryActivity.class);
					startActivityForResult(intent, 0);
				}
			});
			package_route.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.putExtra("ExpressId", ExpressId);
					intent.setClass(getActivity(),
							BaiduMapHistoryActivity.class);
					startActivityForResult(intent, 0);

				}
			});
		}
	}
	
	/**
	 * 返回或保存时调用的方法,返回到主activity
	 */
	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			finish();
		}
		return false;
	}

}
